package com.magima.core.repository;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import android.util.Log;

public class FilePrefRepository extends Repository{
	protected String mFilepath;
	protected Properties mProperties = null;
	protected File mFile = null;
	public FilePrefRepository(StringProcessor processor, String filepath) {
		super(processor);
		mFilepath = filepath;
		mName = filepath;
		mFile = new File(mFilepath);
	}
	public FilePrefRepository(String filepath) {
		this(null, filepath);
	}
	
	private void checkPropertiesLoaded(){
		if ( mProperties == null ) {
			mProperties = new Properties();
			
			File dir = new File(mFile.getParent());
			if (!dir.exists() && !dir.mkdirs()) {
			       Log.e("MAGIMA","Can't create dir"+dir.getPath());
			       return;
			}
			try {
				FileInputStream fi = new FileInputStream(mFile);
				mProperties.load(fi);
				fi.close();			
			} catch (FileNotFoundException e) {
				
			} catch (IOException e) {
				e.printStackTrace();
			}			
		}
	}
	
	private void save(){
		FileOutputStream fo;
		try {
			fo = new FileOutputStream(mFile);
			mProperties.store(fo, null);
			fo.close();			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void saveString(String key, String data) {
		checkPropertiesLoaded();
		
		mProperties.setProperty(key, mProcessor.encodeString(data));
		save();
	}
	
	
	@Override
	public String loadString(String key) {
		checkPropertiesLoaded();
		return mProcessor.decodeString(mProperties.getProperty(key));
	}
	
	@Override
	public List<String> loadAllString() {
		ArrayList<String> list = new ArrayList<String>();
		
		checkPropertiesLoaded();
		for ( Object key : mProperties.keySet() ){
			String str = mProcessor.decodeString(mProperties.getProperty((String) key));
			if ( str != null )
				list.add( str );
		}		
		return list;
	}
	
	@Override
	public void remove(String key){
		checkPropertiesLoaded();
		mProperties.remove(key);
		save();
	}
	
	@Override
	public void remove(){
		File f = new File(mFilepath);
		if ( f.exists() )
			f.delete();
	}
}
